package cn.bitkit.tools.file;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

import cn.bitkit.tools.common.IOUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

/**
 * Files是jdk8以上才支持
 * @author changbo
 *
 */
@Slf4j
public class FileHelper {

	public static int READ = 0;
	public static int APPEND = 1;
	public static int WRITE = 2;
	
	private BufferedReader reader;
	private BufferedWriter writer;

	@SneakyThrows
	private FileHelper(String fileName, int type) {
		if(!new File(fileName).exists()) {
			FileUtil.createFile(fileName);
		}
		Path path = Paths.get(fileName);
		if(type == READ) {
			reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
		}else if (type == APPEND) {
			writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
		}else{
			writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.TRUNCATE_EXISTING);
		}
	}
	
	public static FileHelper getFileHelper(String fileName, int type) {
		return new FileHelper(fileName, type);
	}

	public static FileHelper getReader(String fileName) {
		return new FileHelper(fileName, READ);
	}

	public static FileHelper getWriter(String fileName) {
		return new FileHelper(fileName, WRITE);
	}

	public static FileHelper getAppender(String fileName) {
		return new FileHelper(fileName, APPEND);
	}
	
	public void close() {
		IOUtil.close(reader);
		IOUtil.flush(writer);
		IOUtil.close(writer);
	}

	@SneakyThrows
	public String readLine() {
		return reader.readLine();
	}

	
	public void skip(int skip) {
		for(int i=0; i<skip; i++) {
			readLine();
		}
	}

	@SneakyThrows
	public void write(String str) {
		writer.write(str);
	}

	@SneakyThrows
	public void writeLine(String str) {
		writer.write(str+"\n");
	}
}
